
--#include "data\config\store\NPCStore.lua" once
--#include "data\functions\player.lua" once
--#include "data\config\quest\MiscQuest.lua" once	--任务相关

NpcCommonFunc.NPCTradeInfoToClient = function(sysarg, typeid)
	typeid = tonumber( typeid ) 
	local sellconfig = NPCStore[typeid]

	if not sellconfig or sellconfig.npcid ~= (typeid-1) then
		return
	end

	sellconfig = NPCStore[typeid+1]
	local netPack = DataPack.allocPacket(sysarg,133,3)  --申请一个数据包
	if netPack then
		local len_c_pack = table.getn(sellconfig)
		DataPack.writeChar(netPack,len_c_pack)
		for i = 1, len_c_pack do
			local s = sellconfig[i]
			DataPack.writeString(netPack,s.selltip)

			local silen = table.getn(s.items)
			DataPack.writeByte(netPack,silen)

			for x = 1, silen do
				DataPack.writeWord(netPack, s.items[x])
			end
		end
		DataPack.writeChar(netPack, typeid)
		DataPack.flush(netPack)
	
	end
end

--显示一个任务的内容，ms是任务的配置表，state 1：可接	2：可完成	3：进行中
function NpcCommonFunc.ShowQuestTalk(sysarg, questId, state)
	questId = tonumber(questId)
	state = tonumber(state)
	local content = System.getQuestDialog(questId, state)
	local btnstr = ""
	if state == 1 then		
		btnstr = "<#BN"..Lang.Event.e00003.."/@commonAcceptMissions," .. questId .. ">"
	elseif state == 2 then
		local doubleRwd = ""
		local doubleState, multiAward, mustUseYB = getQuestDoubleExpGold(sysarg, questId)
		if doubleState > 0 then
			local tipsFormat = Lang.ScriptTips.zf058
			if mustUseYB then
				tipsFormat = Lang.ScriptTips.zf059
			end
			local multiStr = string.format(Lang.Event.e00005B, multiAward)
			local tipStr = string.format(tipsFormat, doubleState,multiAward)
			doubleRwd = string.format("<#BN%s/@getDoubleReward,%d,%d><#BT%s/@OnCancleBtn>", multiStr, questId, doubleState, tipStr)
		end
		btnstr = "<#BN"..Lang.Event.e00003A.."/@CompleteMession," .. questId .. ">" .. doubleRwd
	else
		if System.getQuestType(questId) > 0 then
			btnstr = string.format("<#BN%s/@requestGiveupQuest,%d>", Lang.Event.e00031, questId)
		else
			btnstr = string.format("<#BN%s/@CloseNpcDialog>%s", Lang.Event.e00032, btnstr)
		end
		
	end
	return string.format("\n%s<@QuestAwardDesc,%d>\n%s",content,questId,btnstr)
end


function NpcCommonFunc.commonAcceptMissions(sysarg, mission, boAction)
	local questId = tonumber(mission)
	local ms = QuestCallBackCfg[questId]
	if ms and ms.PromCheck then
		if QuestCheckFunc[ms.PromCheck] then
			ck,id = QuestCheckFunc[ms.PromCheck](sysarg, questId, unpack(ms.PromCheckArg or {}))
			if not ck then
				Actor.sendTipmsg(sysarg,id,ttDialog)
				return
			end
		end
	end
  
	if Actor.getQuestCount(sysarg) >= 30 then
		Actor.sendTipmsg(sysarg,Lang.ScriptTips.x00044,ttTipmsgWindow)
	else
		local acceptResult = false
		local questAgainGold = getQuestDoubleExpGold(sysarg, questId, true)
		if questAgainGold > 0 then
			local myGold = Actor.getIntProperty(sysarg,PROP_ACTOR_YUANBAO)
			if myGold < questAgainGold then
				local msgStr = string.format(Lang.ScriptTips.zf048, questAgainGold)
				Actor.sendTipmsg(sysarg, msgStr, ttDialog)
				return
			end
			if boAction then
				if Actor.changeMoney(sysarg, mtYuanbao, -questAgainGold, GameLog.clUseEntrust, Lang.LogTips.yb002) then
					acceptResult = Actor.addQuest( sysarg, questId, true )
				end
			else
				local NPChandle = Actor.getTargetHandle(sysarg)
				local noticeStr = string.format(Lang.ScriptTips.zf106, questAgainGold)
				local ensureStr = string.format("%s/useYbAccpetQst,%d", Lang.ScriptTips.mt00021, questId)
				Actor.messageBox(sysarg, NPChandle,0, noticeStr, ensureStr, Lang.ScriptTips.mt00022.."/OnCancleBtn", nil)
				return
			end
		else
			acceptResult = Actor.addQuest( sysarg, questId)
		end
		if acceptResult then
			if ms and ms.PromCallBack then
				if QuestAcceptFunc[ms.PromCallBack] then	
					QuestAcceptFunc[ms.PromCallBack](sysarg, questId, unpack(ms.PromCallBackArg or {}))
				end
			end
			return continueQuestTalk( sysarg )
		end
	end
	Actor.closeNPCDialog( sysarg )
end

function NpcCommonFunc.useYbAccpetQst( sysarg, questId )
	questId = tonumber(questId)
	if Actor.hasQuest(sysarg, questId) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.zf107, ttFlyTip)		
		return
	end
	return NpcCommonFunc.commonAcceptMissions( sysarg, questId, true)
end



function NpcCommonFunc.CompleteMession(sysarg, mission, ...)
	local questId = tonumber(mission)
	local award = -1
	if arg.n > 0 then 
		award = arg[1]
	end
 
	if Actor.finishQuest( sysarg, questId, award ) then
		OnPlayerFinishQuest(sysarg, questId)
		--onFinishQuest(sysarg, questId)
		return continueQuestTalk( sysarg )
	end
	
	Actor.closeNPCDialog( sysarg )
end


function NpcCommonFunc.getDoubleReward( sysarg, mission )
	local nQid = tonumber(mission)
	if Actor.getDoubleQuestAward(sysarg, nQid) then
		return continueQuestTalk( sysarg )
	end
end



-- 对话框 取消 按钮的函数
function NpcCommonFunc.OnCancleBtn(sysarg)
end

function NpcCommonFunc.requestGiveupQuest( sysarg, questId )
	questId = tonumber(questId)
	if Actor.giveupQuest(sysarg, questId) then
		local questName = System.getQuestTitle( questId )
		Actor.sendTipmsg( sysarg, string.format(Lang.ScriptTips.x00200, questName),ttFlyTip )
		return continueQuestTalk( sysarg )
	end
	Actor.closeNPCDialog(sysarg)
end


function NpcCommonFunc.CloseNpcDialog(sysarg)
	Actor.closeNPCDialog(sysarg)
end

function continueQuestTalk(sysarg)
	--如果交任务后还有可继续的任务状态，则返回主界面
	local newState = Actor.getQuestStateType( sysarg )
	if newState == 1 or newState == 2 then
		return commonQuestNpcMain(sysarg)
	else
		Actor.closeNPCDialog( sysarg )
	end
end

function commonQuestNpcMain(sysarg,func)
	local qc = 0
	local state = 0
	local qid = 0	
	local mission,qc,qid,state = Actor.formatQuestState( sysarg,qc,qid,state )        --通过引擎格式化任务状态
	if qc == 1 and func == nil then
		return NpcCommonFunc.ShowQuestTalk( sysarg, qid, state), true
	end
	return mission, false
end


function getQuestDoubleExpGold( sysarg, nQid, boAgain )
	local questGold = 0
	local questRate = 0
	local questMulti = 0
	local mustUseYB = false
	local finTimes = Actor.getQuestTimes(sysarg, nQid, boAgain)
	if boAgain then
		questGold = Actor.getQuestAcceptAgain(sysarg, nQid)
		finTimes = finTimes + 1
		questRate = GlobalConfig.fQuestAcceptAgainRate
	else
		questGold, questMulti, mustUseYB = Actor.getQuestDoubleInfo(sysarg, nQid, 0, mustUseYB)
		finTimes = finTimes - 1
		if finTimes < 0 then
			finTimes = 0
		end
		questRate = GlobalConfig.fQuestDoubleAwardRate
	end
	if questGold > 0 then
		return math.floor(questGold * ( 1 + finTimes * questRate)), questMulti,mustUseYB
	end
	return 0, questMulti,mustUseYB
end




function onFinishQuest(sysarg, qid)
	local ms = QuestCallBackCfg[qid]
	if ms and ms.CompCallBack then
		if QuestFinishFunc[ms.CompCallBack] then
			QuestFinishFunc[ms.CompCallBack](sysarg, qid, unpack(ms.CompCallbackArg or {}))
		end
	end
end

function onGiveUpQuest(sysarg, qid)
	local ms = QuestCallBackCfg[qid]
	if ms and ms.GiveUpCallBack then
		if QuestGiveUpFunc[ms.GiveUpCallBack] then
    		QuestGiveUpFunc[ms.GiveUpCallBack]( sysarg, qid, unpack(ms.GiveUpCallBackArg or {}) )
    	end
	end
end

---------------------------------------------------------------------------------------
-- 过程任务（对话任务）
function NpcCommonFunc.talkWithNPC(sysarg, qid, tid)
	local qid = tonumber(qid)
	local tid = tonumber(tid)
	local q
	
	for idx, quest in ipairs(PassMs or {}) do
		if quest.id == qid then
			q = quest
			break
		end
	end
	if not q then
		return ""
	end
	local index = 1

	--[[for i = 1,#q.target do
		if q.target[i].id == tid then
			index = i
		end
	end ]]

	Actor.setQuestValue(sysarg,qid,tid,1)
	if q.PassMsTip[index] then
		return string.format("%s<#BL%s/@CloseNpcDialog>", q.PassMsTip[index], Lang.ScriptTips.x00079)
	else
		Actor.closeNPCDialog(sysarg)
	end
	return 
end

function GetCfgFromTab( qid, qSubTab )
	for k, v in ipairs(qSubTab or {}) do
		if v.id == qid then
			return v
		end
	end
	return nil
end

function NpcCommonFunc.OnQuestTalk( sysarg, qid, targetId )
	local strTalk = ""
	if Actor.hasQuest(sysarg, qid) and not Actor.canFinishQuest(sysarg, qid ) then
		local randId = Actor.getQuestRandId(sysarg, qid)
		if randId >= 0 then
			local q = GetCfgFromTab(qid, PassMs)
			if q then
				local qCfg = q.target[randId + 1]
				if qCfg and qCfg.id == targetId then
					local questType = System.getQuestTypeName(qid)
					local questTitle = System.getQuestTitle(qid)
					if questType and questTitle then
						questTitle = string.format("（%s）%s", questType, questTitle)
					else
						questTitle = Lang.Event.e00028
					end
					strTalk = string.format("<\n%s/@talkWithNPC,%d,%d>", questTitle, qid, targetId)
				end
			end
		end
	end
	return strTalk
end

-- 和法随机索引
function GetRandIndex(tbl) -- 权重表,例如 {1,3,7}
	local totalWeight = 0;
	for i = 1, #(tbl) do
		totalWeight = totalWeight + tbl[i] or 0;
	end
	local r = math.random(totalWeight);
	local s = 0;
	for i = 1, #(tbl) do
		s = s + tbl[i] or 0;
		if s >= r then
			return i;
		end
	end
end


